<template>
    <div style="height:100%;">
      <div>
        <div class='content-title'>
          <div class='content-title-parent'>电商管理</div>
          /
          <div class='content-title-child'>优惠券管理</div>
        </div>
        <hr class='content-hr'/>
      </div>
      <!--表格筛选条件-->
      <el-row style="margin-top:10px" class='couponClass'>
        <el-form v-model="filterForm" ref="filterForm":inline="true">
          <el-form-item label="优惠券编号：" >
            <el-input style="width:160px" @keyup.native="filterForm.couponId=filterForm.couponId.replace(/[^\w]/g, '')" clearable v-model="filterForm.couponId"></el-input>
          </el-form-item>
          <el-form-item label="优惠券名称：" >
            <el-input style="width:160px" @keyup.native="filterForm.couponName=filterForm.couponName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" clearable v-model.trim="filterForm.couponName"></el-input>
          </el-form-item>
          <el-form-item label="所属机场：" >
            <el-cascader
              clearable
              style="width:160px"
              v-model="filterForm.airportList"
              expand-trigger="hover"
              :options="filterForm.airportNameList"
              @change="selectAirport('filterForm')"
              :props="airportProps">
            </el-cascader>
          </el-form-item>
          <div style="clear:both"></div>
          <el-form-item label="所属状态：" style="margin-top:6px">
            <el-checkbox-group v-model="filterForm.statusList" >
              <el-checkbox label="已生效"></el-checkbox>
              <el-checkbox label="未上线"></el-checkbox>
              <el-checkbox label="待生效"></el-checkbox>
              <el-checkbox label="已失效"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="" style="margin-top:6px">
            <el-button type="primary" style="background-color:#2280E9;border-color:#2280E9;width:60px;margin-left:10px" @click="submitSearch()">查询</el-button>
          </el-form-item>
          <el-button type="warning" style="float:right;margin-top:6px;margin-right:20px " @click="addVisable = true">新增优惠券</el-button>
        </el-form>
      </el-row>
      <!--查询表格数据-->
      <el-row>
        <el-table
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          class='couponClassTabel'
          :data="filterFormFro.tableData" 
          :border="true" 
          :cell-class-name="tabelCellClassName"
          :row-class-name="tableRowClassName"
          :header-cell-class-name = "tableHeaderClassName"
          v-bind:style="{width: tableWidth + 'px'}">
            <el-table-column prop="index" label="序号" width="50">
            </el-table-column>
            <el-table-column prop="couponId" label="优惠券编号" >
            </el-table-column>
            <el-table-column prop="couponName" label="优惠券名称" >
            </el-table-column>
            <el-table-column prop="value" label="面值" >
            </el-table-column>
            <el-table-column prop="airportTerminal" label="机场航站楼" >
            </el-table-column>
            <el-table-column prop="placeName" label="所属商家">
            </el-table-column>
            <el-table-column prop="onlineTime" label="上线时间" >
            </el-table-column>
            <el-table-column prop="issuedNum" label="发放数量">
            </el-table-column>
            <el-table-column prop="takenNum" label="使用数量" >
            </el-table-column>
            <el-table-column prop="state" label="状态">
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button
                :type="scope.row.state === '已生效' || scope.row.state === '已失效' ? 'warning' : 'primary'"
                size="mini"
                @click="handleEdit(scope.$index, scope.row, scope.row.state)">{{scope.row.tag}}</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 表格下方分页 -->
      <el-row>
        <div class="pagination" style="text-align:center" v-show="paginationVisible">
            <el-pagination
              @current-change="handleCurrentChange"
              background
              :current-page="filterFormFro.currentPage"
              :page-size="15"
              layout="total, prev, pager, next"
              :page-count="filterFormFro.totalPage">
            </el-pagination>
        </div>
      </el-row>
      <!-- 添加优惠券信息弹窗 -->
      <el-dialog title="增加优惠券："   :visible.sync="addVisable"
          :closeOnClickModal="false" 
          width="650px"
          class="categoryManaDialog couponManaDialog"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="resetForm('addForm')">
          <el-dialog
            width="650px"
            title="选择商家"
            class='categoryManaDialog'
            :visible.sync="innerVisible"
            append-to-body
            @open="setChildType('addForm')">
            <select-business @set-id="getSetId" @close-event="closeDialog()" :businessId="addForm.businessId" ref="selectbusiness"></select-business>
          </el-dialog>
          <div class="inner">
            <div class="innerbox">
              <el-form :model='addForm' ref="addForm" :rules="addRules" label-width="180px">
                  <el-form-item label="优惠券名称："  prop="couponName">
                    <el-input style='width:240px' @keyup.native="addForm.couponName=addForm.couponName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" v-model.trim="addForm.couponName"></el-input>
                  </el-form-item>
                  <el-form-item label="优惠券面值："  prop="value">
                    <el-checkbox v-model="addForm.isFixedValue" style="float:left">定额</el-checkbox>
                    <el-input style='width:150px;float:left;margin-left:15px'  auto-complete="off" type="number" v-model.number="addForm.value"></el-input>
                    <span style="margin-left:10px">元</span>
                  </el-form-item>
                  <el-form-item label="满额使用："  prop="fullUse">
                    <el-input style='width:240px' v-model.number="addForm.fullUse" type="number"></el-input>
                    <span style="margin-left:10px;color:#409EFF">0为无限制</span>
                  </el-form-item>
                  <el-form-item label="发放方式：" prop="couponSendType">
                    <el-radio-group v-model="addForm.couponSendType" style='width:50%' >
                      <el-radio label="发放" value="1"></el-radio>
                      <el-radio label="派发" value="2"></el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="发放机场：" prop='airportName'>
                    <el-cascader
                        style="width:240px"
                        v-model="addForm.airportList"
                        expand-trigger="hover"
                        :options="addForm.airportNameList"
                        @change="selectAirport('addForm')"
                        :props="airportProps">
                    </el-cascader>
                  </el-form-item>
                  <!-- <el-form-item label="发放人群：" prop="peopleLimit">
                    <el-select v-model="addForm.peopleLimit" clearable placeholder="请选择发放人群" style='width:50%' >
                      <el-option
                          v-for="item in peopleLimitList"
                          :key="item"
                          :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item> -->
                  <el-form-item label="所属商家：" prop="businessAllName">
                    <el-input style="width:240px" :readonly="true" v-model="addForm.businessAllName" v-show="addBusVisible"></el-input>
                    <el-button icon="el-icon-circle-plus" style="width:80px" type="primary" @click="clickSelectBus('addForm')"></el-button>
                  </el-form-item>
                  <el-form-item label="发放数量："  prop="issuedNum">
                    <el-input style='width:240px' v-model.number="addForm.issuedNum" type="number"></el-input>
                    <span style="margin-left:10px;color:#409EFF">0为无限制</span>
                  </el-form-item>
                  <el-form-item label="限领数量："  prop="limitNum">
                    <el-input style='width:240px' v-model.number="addForm.limitNum" type="number"></el-input>
                    <span style="margin-left:10px;color:#409EFF">0为无限制</span>
                  </el-form-item>
                  <el-form-item label="已领基数："  prop="baseNum">
                    <el-input style='width:240px' v-model.number="addForm.baseNum" type="number"></el-input>
                  </el-form-item>
                  <el-form-item label="上线时间："  prop="onlineTime">
                    <el-date-picker
                      style="width:240px"
                      :picker-options="pickerOptions0"
                      v-model="addForm.onlineTime"
                      type="datetime"
                      placeholder="选择上线时间">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="生效时间："  prop="effectiveTime">
                    <el-date-picker
                      style="width:240px"
                      :picker-options="pickerOptions0"
                      v-model="addForm.effectiveTime"
                      type="datetime"
                      placeholder="选择生效时间">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="失效时间："  prop="expireTime">
                    <el-date-picker
                      style="width:240px"
                      :picker-options="pickerOptions0"
                      v-model="addForm.expireTime"
                      type="datetime"
                      placeholder="选择失效时间">
                    </el-date-picker>
                  </el-form-item>
              </el-form>
            </div>
          </div>
          <el-form label-width="180px">
            <el-form-item label="">
              <el-button type="primary" style="margin-top:0px" @click="submitAdd()">保 存</el-button>
            </el-form-item>
          </el-form>
      </el-dialog>
      <!-- 编辑优惠券信息弹窗 -->
      <el-dialog title="编辑优惠券信息:"   :visible.sync="editVisable"
        :closeOnClickModal="false" 
        width="650px"
        class="categoryManaDialog couponManaDialog"
        :close-on-click-modal="false" 
        :close-on-press-escape="false"
        @close="resetForm('editForm')">
        <el-dialog
          width="650px"
          class="categoryManaDialog"
          title="选择商家"
          :visible.sync="innerVisible"
          @open="setChildType('editForm')"
          append-to-body>
          <select-business @set-id="getSetId" @close-event="closeDialog()" :businessId="addForm.businessId" ref="selectbusiness"></select-business>
        </el-dialog>
        <div class="inner">
          <div class="innerbox">
            <el-form :model='editForm' ref="editForm" :rules="editRules"  label-width="180px">
              <el-form-item label="优惠券名称："  prop="couponName">
                <el-input style='width:240px' @keyup.native="editForm.couponName=editForm.couponName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" :disabled="isEdit" v-model.trim="editForm.couponName"></el-input>
              </el-form-item>
              <el-form-item label="优惠券面值："  prop="value">
                <el-checkbox v-model="editForm.isFixedValue" :disabled="isEdit" style="float:left">定额</el-checkbox>
                <el-input style='width:150px;float:left;margin-left:15px' :disabled="isEdit"  type="number" v-model.number="editForm.value"></el-input>
                <span style="margin-left:10px">元</span>
              </el-form-item>
              <el-form-item label="满额使用："  prop="fullUse">
                <el-input style='width:240px' :disabled="isEdit" v-model.number="editForm.fullUse" type="number"></el-input>
                <span style="margin-left:10px;color:#409EFF">0为无限制</span>
              </el-form-item>
              <el-form-item label="发放方式：">
                <el-radio-group v-model="editForm.couponSendType" :disabled="isEdit" style='width:240px'>
                  <el-radio :label="1">领取</el-radio>
                  <el-radio :label="2">派发</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="发放机场：" prop='airportName'>
                <el-cascader
                  :disabled="isEdit"
                  style='width:240px'
                  v-model="editForm.airportList"
                  expand-trigger="hover"
                  :options="editForm.airportNameList"
                  @change="selectAirport('editForm')"
                  :props="airportProps"
                >
                </el-cascader>
              </el-form-item>
              <!-- <el-form-item label="发放人群：">
                <el-select v-model="editForm.peopleLimit" :disabled="isEdit" placeholder="请选择发放人群" style='width:50%' >
                  <el-option label="近一个月登录用户" value="0"></el-option>
                  <el-option label="所有用户" value="1"></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="所属商家:" prop='businessAllName'>
                <el-input style="width:240px" :disabled="isEdit" :readonly="true" v-model="editForm.businessAllName" v-show="editBusVisible"></el-input>
                <el-button icon="el-icon-circle-plus" style="width:80px"  :disabled="isEdit" type="primary" @click="clickSelectBus('editForm')"></el-button>
              </el-form-item>
              <el-form-item label="发放数量："  prop="issuedNum">
                <el-input style='width:240px' :disabled="isEdit" v-model.number="editForm.issuedNum" type="number"></el-input>
                <span style="margin-left:10px;color:#409EFF">0为无限制</span>
              </el-form-item>
              <el-form-item label="限领数量："  prop="limitNum">
                <el-input style='width:240px' :disabled="isEdit" v-model.number="editForm.limitNum" type="number"></el-input>
                <span style="margin-left:10px;color:#409EFF">0为无限制</span>
              </el-form-item>
              <el-form-item label="已领基数："  prop="baseNum">
                <el-input style='width:240px'  v-model.number="editForm.baseNum" type="number"></el-input>
              </el-form-item>
              <el-form-item label="上线时间："  prop="onlineTime">
                <el-date-picker
                :disabled="isEdit"
                  style="width:240px"
                  :picker-options="pickerOptions0"
                  v-model="editForm.onlineTime"
                  type="datetime"
                  placeholder="选择上线时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="生效时间："  prop="effectiveTime">
                <el-date-picker
                  :disabled="isEdit"
                  style="width:240px"
                  :picker-options="pickerOptions0"
                  v-model="editForm.effectiveTime"
                  type="datetime"
                  placeholder="选择生效时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="失效时间："  prop="expireTime">
                <el-date-picker
                  style="width:240px"
                  :picker-options="pickerOptions0"
                  v-model="editForm.expireTime"
                  type="datetime"
                  placeholder="选择失效时间">
                </el-date-picker>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <el-form label-width="180px">
          <el-form-item label="">
            <el-button type="primary" style="margin-top:0px" @click="submitEdit()">保 存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 查看优惠券详情弹窗 -->
      <el-dialog title="查看优惠券详情:" :visible.sync="detailVisable"
        :modal="false"
        class="categoryManaDialog couponDetailDialog"
        :closeOnClickModal="false"
        :close-on-press-escape="false"
        width="600px">
        <div class="inner">
          <div class="innerbox" style="">
            <el-form style="" v-model="editForm" label-width="110px">
              <el-form-item label="优惠券名称：">
                <span>{{editForm.couponName}}</span>
              </el-form-item>
              <el-form-item label="优惠券面值：">
                <span style="margin-left:10px">{{editForm.isFixedValueContent}}</span>
                <span style="margin-left:10px">{{editForm.value}}</span>
                <span style="margin-left:10px">元</span>
              </el-form-item>
              <el-form-item label="满额使用：">
                <span>{{editForm.fullUse}}</span>
              </el-form-item>
              <el-form-item label="发放方式：">
                <span>{{editForm.couponSendTypeValue}}</span>
              </el-form-item>
              <el-form-item label="发放机场：">
                <span>{{editForm.airportName + editForm.terminalName}}</span>
              </el-form-item>
              <el-form-item label="所属商家：">
                <span>{{editForm.businessAllName}}</span>
              </el-form-item>
              <el-form-item label="发放数量：">
                <span>{{editForm.issuedNum}}</span>
              </el-form-item>
              <el-form-item label="限领数量：">
                <span>{{editForm.limitNum}}</span>
              </el-form-item>
              <el-form-item label="已领基数：">
                <span>{{editForm.baseNum}}</span>
              </el-form-item>
              <el-form-item label="上线时间：">
                <span>{{editForm.onlineTime}}</span>
              </el-form-item>
              <el-form-item label="生效时间：">
                <span>{{editForm.effectiveTime}}</span>
              </el-form-item>
              <el-form-item label="失效时间：">
                <span>{{editForm.expireTime}}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-dialog>
    </div>
</template>
<script>
import apiBus from '../../api/businessPlat/apiBus.js'
import SelectBusiness from '../businessPlat/selectBusiness.vue'
import '../../../static/css/businessPlat/common.css'
import '../../../static/css/businessPlat/couponMana.css'
export default {
  mounted () {
    // this.filterFormFro.tableData = this.testData
    this.getCouponListFro()
    this.getAllTerminalFro()
    this.tableWidth = document.body.scrollWidth - 259 - 20
  },
  data () {
    var checkNum = (rule, value, callback) => { // 数字验证
      if (value < 0) {
        callback(new Error('请输入大于等于0的数字'))
      } else {
        callback()
      }
    }
    var checkValue = (rule, value, callback) => { // 优惠券面值验证
      if (value > 500) {
        callback(new Error('优惠券面值最大为500'))
      } else {
        callback()
      }
    }
    var checkInetger = (rule, value, callback) => { // 正整数验证
      if (!Number.isInteger(value) || value < 0) {
        callback(new Error('请输入整数'))
      } else {
        callback()
      }
    }
    var validateIssuedNumAdd = (rule, value, callback) => { // 发放数量验证
      if (value === '' || value === 0 || value === '0') {
        callback(new Error('请请填写发放数量'))
      } else {
        if (this.addForm.baseNum !== '') {
          this.$refs.addForm.validateField('baseNum')
          this.$refs.addForm.validateField('limitNum')
        }
        callback()
      }
    }
    var validateBaseNumAdd = (rule, value, callback) => { // 已领基数验证
      if (value === '') {
        callback(new Error('请填写已领基数'))
      } else if (Number(value) > Number(this.addForm.issuedNum)) {
        callback(new Error('已领基数不能大于发放数量'))
      } else {
        callback()
      }
    }
    var validateLimitNumAdd = (rule, value, callback) => { // 限领数量验证
      if (value === '') {
        callback(new Error('请填写限领数量'))
      } else if (Number(value) > Number(this.addForm.issuedNum)) {
        callback(new Error('限领数量不能大于发放数量'))
      } else {
        callback()
      }
    }
    var validateIssuedNumEdit = (rule, value, callback) => { // 发放数量验证
      if (value === '' || value === 0 || value === '0') {
        callback(new Error('请请填写发放数量'))
      } else {
        if (this.editForm.baseNum !== '') {
          this.$refs.editForm.validateField('baseNum')
          this.$refs.editForm.validateField('limitNum')
        }
        callback()
      }
    }
    var validateBaseNumEdit = (rule, value, callback) => { // 已领基数验证
      if (value === '') {
        callback(new Error('请填写已领基数'))
      } else if (Number(value) > Number(this.editForm.issuedNum)) {
        callback(new Error('已领基数不能大于发放数量'))
      } else {
        callback()
      }
    }
    var validateLimitNumEdit = (rule, value, callback) => { // 限领数量验证
      if (value === '') {
        callback(new Error('请填写限领数量'))
      } else if (Number(value) > Number(this.editForm.issuedNum)) {
        callback(new Error('限领数量不能大于发放数量'))
      } else {
        callback()
      }
    }
    return {
      pickerOptions0: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      addBusVisible: false, // 添加商家输入框是否可见
      editBusVisible: true, // 编辑商家输入框是否可见
      innerVisible: false, // 嵌套弹窗选择增加商家
      paginationVisible: false, // 是否显示
      pointVisible: false,
      Note: '',
      loading: false,
      loadingText: '正在拼命加载中，请稍等......',
      testData: [],
      tableWidth: '', // 表格宽度
      peopleLimitList: ['一个月用户', '两个月用户'],
      filterForm: { // 查询的入参
        airportList: [], // 所选机场和航站楼
        airportName: '',
        airportId: '', // 机场ID
        terminalId: [], // 航站楼ID
        terminalName: [],
        couponId: '',
        couponName: '',
        statusList: ['已生效', '未上线', '待生效', '已失效'],
        airportNameList: []
      },
      filterFormFro: {
        tableData: [],
        totalPage: 0,
        currentPage: 1
      },
      airportNameList: [],
      categoryList: [{
        value: '柜台服务'
      }, {
        value: '候机服务'
      }, {
        value: '行李服务'
      }, {
        value: '金融服务'
      }, {
        value: '生活便利'
      }, {
        value: '娱乐休闲'
      }],
      noteVisible: false,
      formLabelWidth: '30%',
      addForm: {
        couponId: '',
        isFixedValue: true, // 是否定额
        couponName: '', // 优惠券名称
        value: '', // 优惠券面值
        isFixed: '',
        airportName: '', // 发放机场
        businessName: '',
        peopleLimit: '', // 发放人群
        couponSendType: '发放', // 发放方式：
        fullUse: '', // 满额使用
        businessAllName: '', // 所属商家（商家名称+机场航站楼）
        onlineTime: '', // 上线时间：
        effectiveTime: '', // 生效时间
        expireTime: '', // 失效时间
        takenNum: 0, // 已领数量
        limitNum: '', // 限领数量
        issuedNum: '', // 发放数量
        businessId: '',
        baseNum: 0,
        airportList: [],
        terminalId: [],
        terminalName: []
      },
      addVisable: false,
      editVisable: false,
      detailVisable: false,
      isEdit: false, // 设定已生效优惠券只能修改基数和失效时间
      editForm: {
        airportList: ['', ''],
        terminalId: [],
        terminalName: [],
        airportId: '',
        businessAllName: '',
        isFixedValue: true,
        index: 0,
        couponId: '',
        couponName: '',
        value: '',
        isFixed: '',
        airportName: '',
        businessName: '',
        peopleLimit: '1',
        fullUse: '',
        onlineTime: '',
        effectiveTime: '',
        expireTime: '',
        limitNum: '',
        issuedNum: '',
        issuedType: '1',
        takenNum: '',
        isDelete: ''
      },
      deleteForm: {
        label: '',
        num: '',
        number: ''
      },
      airportProps: {
        value: 'label',
        children: 'terminals'
      },
      // 增加优惠券验证规则
      addRules: {
        couponName: [
          { required: true, message: '请填写优惠券名称', trigger: 'blur' },
          { max: 20, message: '优惠券最多20个字符', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请填写优惠券面值', trigger: 'blur' },
          { validator: checkNum, trigger: 'blur' },
          { validator: checkValue, trigger: 'blur' }
        ],
        placeName: [
          { required: true, message: '请输入商场名称', trigger: 'blur' },
          { max: 20, message: '最多20个字符', trigger: 'blur' }
        ],
        fullUse: [
          { required: true, message: '请填写满额使用值', trigger: 'blur' },
          { validator: checkNum, trigger: 'blur' }
        ],
        airportName: [
          { required: true, message: '请选择机场', trigger: 'change' }
        ],
        peopleLimit: [
          { required: true, message: '请选择发放人群', trigger: 'change' }
        ],
        businessAllName: [
          { required: true, message: '请选择所属商家', trigger: 'blur' }
        ],
        issuedNum: [
          { required: true, message: '请填写发放数量', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: validateIssuedNumAdd, trigger: 'blur' }
        ],
        baseNum: [
          { required: true, message: '请填写已领基数', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: validateBaseNumAdd, trigger: 'blur' }
        ],
        limitNum: [
          { required: true, message: '请填写限领数量', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: validateLimitNumAdd, trigger: 'blur' }
        ],
        onlineTime: [
          { required: true, message: '请选择上线时间', trigger: 'blur' }
        ],
        effectiveTime: [
          { required: true, message: '请选择生效时间', trigger: 'blur' }
        ],
        expireTime: [
          { required: true, message: '请选择失效时间', trigger: 'blur' }
        ]
      },
      // 增加优惠券验证规则
      editRules: {
        couponName: [
          { required: true, message: '请填写优惠券名称', trigger: 'blur' },
          { max: 20, message: '优惠券最多20个字符', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请填写优惠券面值', trigger: 'blur' },
          { validator: checkNum, trigger: 'blur' },
          { validator: checkValue, trigger: 'blur' }
        ],
        placeName: [
          { required: true, message: '请输入商场名称', trigger: 'blur' },
          { max: 20, message: '最多20个字符', trigger: 'blur' }
        ],
        fullUse: [
          { required: true, message: '请填写满额使用值', trigger: 'blur' },
          { validator: checkNum, trigger: 'blur' }
        ],
        airportName: [
          { required: true, message: '请选择机场', trigger: 'change' }
        ],
        peopleLimit: [
          { required: true, message: '请选择发放人群', trigger: 'change' }
        ],
        businessAllName: [
          { required: true, message: '请选择所属商家', trigger: 'blur' }
        ],
        issuedNum: [
          { required: true, message: '请填写发放数量', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: validateIssuedNumEdit, trigger: 'blur' }
        ],
        baseNum: [
          { required: true, message: '请填写已领基数', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: validateBaseNumEdit, trigger: 'blur' }
        ],
        limitNum: [
          { required: true, message: '请填写限领数量', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: validateLimitNumEdit, trigger: 'blur' }
        ],
        onlineTime: [
          { required: true, message: '请选择上线时间', trigger: 'blur' }
        ],
        effectiveTime: [
          { required: true, message: '请选择生效时间', trigger: 'blur' }
        ],
        expireTime: [
          { required: true, message: '请选择失效时间', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    SelectBusiness
  },
  methods: {
    // 处理后台发来的数据以显示在下拉框中（主要针对机场和航站楼，使其可以二级联动选择）
    setDropdown (testAirport, form) {
      let parentIdList = []
      let totalList = []
      for (let i = 0; i < testAirport.length; i++) {
        if (parentIdList.indexOf(testAirport[i].airportId) === -1) {
          parentIdList.push(testAirport[i].airportId)
          totalList.push({
            label: testAirport[i].figureThree + ' ' + testAirport[i].airportName,
            airportId: testAirport[i].airportId,
            terminals: []
          })
        }
      }
      for (let i = 0; i < totalList.length; i++) {
        testAirport.forEach((item) => {
          if (item.airportId === totalList[i].airportId) {
            totalList[i].terminals.push({
              label: item.terminalName,
              terminalId: item.terminalId
            })
          }
        })
      }
      if (form === 'filterForm') {
        for (let i = 0; i < totalList.length; i++) {
          totalList[i].terminals.push({
            label: '全部',
            terminalId: ''
          })
        }
      }
      this[form].airportNameList = totalList
    },
    // 打开添加商家弹窗时向子页面传递表单类型“add”或者“edit”
    setChildType (form) {
      this.$nextTick(() => {
        let airportId = parseInt(this[form].airportId)
        let terminalId = ''
        this[form].terminalId.length > 1 ? terminalId = '' : terminalId = parseInt(this[form].terminalId[0])
        this.$refs.selectbusiness.setPageType(form, airportId, terminalId)
      })
    },
    // 弹窗选取商家，只有在选择机场之后才可
    clickSelectBus (Form) {
      if (this[Form].airportName !== '') {
        this.innerVisible = true
      } else {
        this.innerVisible = false
        this.$message.warning('请先选择发放机场！')
      }
    },
    // 从子件弹窗获得所选id和名称
    getSetId (para) {
      para.type === 'editForm' ? this.editBusVisible = true : this.addBusVisible = true
      this[para.type].businessAllName = para.row.placeName + '(' + para.row.businessAddress + ')'
      this[para.type].businessId = para.id
    },
    // 关闭子弹窗
    closeDialog () {
      this.innerVisible = false
    },
    // 将时间从时间戳转化为字符串显示
    formatDateFro (now) {
      var year = now.getFullYear()
      var month = now.getMonth() + 1
      month = month < 10 ? '0' + month : month
      var date = now.getDate()
      date = date < 10 ? ('0' + date) : date
      var hour = now.getHours()
      hour = hour < 10 ? ('0' + hour) : hour
      var minute = now.getMinutes()
      minute = minute < 10 ? ('0' + minute) : minute
      var second = now.getSeconds()
      second = second < 10 ? ('0' + second) : second
      return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
    },
    // 下拉框选择机场及航站楼
    selectAirport (Form) {
      for (let i = 0; i < this[Form].airportNameList.length; i++) {
        this[Form].terminalId = []
        if (this[Form].airportNameList[i].label === this[Form].airportList[0]) {
          this[Form].airportId = this[Form].airportNameList[i].airportId
          this[Form].airportName = this[Form].airportNameList[i].label
          for (let m = 0; m < this[Form].airportNameList[i].terminals.length; m++) {
            if (this[Form].airportList[1] === this[Form].airportNameList[i].terminals[m].label && this[Form].airportList[1] !== '全部') {
              this[Form].terminalId.push(this[Form].airportNameList[i].terminals[m].terminalId)
              this[Form].terminalName.push(this[Form].airportNameList[i].terminals[m].label)
              break
            } else if (this[Form].airportList[1] === '全部') {
              if (this[Form].airportNameList[i].terminals[m].label !== '全部') {
                this[Form].terminalId.push(this[Form].airportNameList[i].terminals[m].terminalId)
                this[Form].terminalName.push(this[Form].airportNameList[i].terminals[m].label)
              }
            }
          }
          break
        }
      }
    },
    /** 提交后台相关函数 */
    // 查询所有航站楼
    getAllTerminalFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'airportService_v1'
        }),
        body: JSON.stringify({})
      }
      apiBus.getAllTerminal(para).then(res => {
        let terminalList = []
        if (res.data.body.result === 1000) {
          terminalList = res.data.body.content.list
          this.setDropdown(terminalList, 'filterForm')
          this.setDropdown(terminalList, 'addForm')
          this.setDropdown(terminalList, 'editForm')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 查看优惠券列表
    getCouponListFro () {
      this.filterFormFro.tableData = []
      this.loading = true
      this.paginationVisible = false
      let terminalId = ''
      this.filterForm.terminalId.length > 1 ? terminalId = '' : terminalId = parseInt(this.filterForm.terminalId[0])
      let state = ''
      this.filterForm.statusList.length === 0 ? state = null : state = this.filterForm.statusList
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          pageNum: parseInt(this.filterFormFro.currentPage), // 当前页面数
          couponId: this.filterForm.couponId,
          couponName: this.filterForm.couponName,
          airportId: parseInt(this.filterForm.airportId),
          states: state,
          terminalId: terminalId
        })
      }
      apiBus.getCouponList(para).then(res => {
        this.loading = false
        if (res.data.body.result === 1000) {
          let resData = res.data.body.content.list
          if (resData.length > 0) {
            this.$message.success('成功获取优惠券信息！')
            this.filterFormFro.tableData = resData
            for (let i = 0; i < this.filterFormFro.tableData.length; i++) {
              this.filterFormFro.tableData[i].airportTerminal = resData[i].figureThree + ' ' + resData[i].airportName + resData[i].terminalName
              this.filterFormFro.tableData[i].index = (parseInt(this.filterFormFro.currentPage) - 1) * 15 + i + 1
              this.filterFormFro.tableData[i].onlineTime = this.formatDateFro(new Date(resData[i].onlineTime))
              if (this.filterFormFro.tableData[i].state === '已生效') {
                this.filterFormFro.tableData[i].tag = '编辑'
              } else if (this.filterFormFro.tableData[i].state === '已失效') {
                this.filterFormFro.tableData[i].tag = '查看'
              } else { // 未上线和待生效
                this.filterFormFro.tableData[i].tag = '编辑'
              }
            }
            this.filterFormFro.totalPage = res.data.content.totalPage
            this.filterFormFro.totalPage > 1 ? this.paginationVisible = true : this.paginationVisible = false
          } else {
            this.$message.warning('没有查询到任何优惠券！')
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },
    // 增加商家
    addCouponListFro () {
      let terminalId = ''
      this.addForm.terminalId.length > 1 ? terminalId = '' : terminalId = parseInt(this.addForm.terminalId[0])
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          couponName: this.addForm.couponName,
          airportId: parseInt(this.addForm.airportId),
          value: parseFloat(this.addForm.value),
          fullUse: parseFloat(this.addForm.fullUse),
          businessId: parseInt(this.addForm.businessId),
          issuedNum: parseInt(this.addForm.issuedNum),
          limitNum: parseInt(this.addForm.limitNum),
          baseNum: parseInt(this.addForm.baseNum),
          onlineTime: this.formatDateFro(new Date(this.addForm.onlineTime)),
          effectiveTime: this.formatDateFro(new Date(this.addForm.effectiveTime)),
          expireTime: this.formatDateFro(new Date(this.addForm.expireTime)),
          couponSendType: parseInt(this.addForm.couponSendType),
          terminalId: terminalId
        })
      }
      apiBus.addCouponList(para).then(res => {
        this.pointVisible = false
        if (res.data.body.result === 1000) {
          this.filterFormFro.currentPage = 1
          this.getCouponListFro()
          this.$message.success('成功添加优惠券！')
          this.addVisable = false
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 编辑分类
    editCouponListFro () {
      let terminalId = ''
      this.editForm.terminalId.length > 1 ? terminalId = '' : terminalId = parseInt(this.editForm.terminalId[0])
      let para = {
        header: JSON.stringify({
          'token': sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          couponName: this.editForm.couponName,
          airportId: parseInt(this.editForm.airportId),
          value: parseFloat(this.editForm.value),
          fullUse: parseFloat(this.editForm.fullUse),
          businessId: parseInt(this.editForm.businessId),
          issuedNum: parseInt(this.editForm.issuedNum),
          limitNum: parseInt(this.editForm.limitNum),
          baseNum: parseInt(this.editForm.baseNum),
          takenNum: parseInt(this.editForm.takenNum),
          onlineTime: this.formatDateFro(new Date(this.editForm.onlineTime)),
          effectiveTime: this.formatDateFro(new Date(this.editForm.effectiveTime)),
          expireTime: this.formatDateFro(new Date(this.editForm.expireTime)),
          couponSendType: parseInt(this.editForm.couponSendType),
          terminalId: terminalId,
          couponId: this.editForm.couponId
        })
      }
      apiBus.editCouponList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.filterFormFro.currentPage = 1
          this.getCouponListFro()
          this.$message.success('成功编辑该优惠券')
          this.editVisable = false
          this.resetForm('editForm')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 向后台发送请求删除分类
    deleteCouponListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          couponId: this.deleteForm.couponId
        })
      }
      apiBus.deleteCouponList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.filterFormFro.currentPage = 1
          this.$message.success('成功删除优惠券！')
          this.getCouponListFro()
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 分页每页数目改变时
    handleSizeChange (val) {
      this.filterFormFro.pageSize = val
      this.filterFormFro.currentPage = 1
    },
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterFormFro.currentPage = val
      this.getCouponListFro()
    },
    // 重置表单
    resetForm (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
      this[formName].businessAllName = ''
      this[formName].terminalId = []
      this[formName].terminalName = []
      this[formName].airportId = ''
      if (formName === 'addForm') {
        this.addForm.airportList = []
        this.addBusVisible = false
      }
    },
    // 点击“保存”增加优惠券弹窗
    submitAdd () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          if (this.addForm.airportName === '') {
            this.$message.warning('请选择所属商家！')
            return false
          }
          this.addCouponListFro()
          this.resetForm('addForm')
        } else {
          return false
        }
      })
    },
    // 点击“保存”编辑优惠券弹窗
    submitEdit () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          if (this.editForm.airportName === '') {
            this.$message.warning('请选择所属商家！')
            return false
          }
          this.editCouponListFro()
        } else {
          return false
        }
      })
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 根据数据内容设置表格“状态”样式
    tabelCellClassName ({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 9) {
        if (row.state === '已生效') {
          return 'cellClassExecuted'
        } else if (row.state === '已失效') {
          return 'cellClassNo'
        } else {
          return 'cellClass'
        }
      }
    },
    // 点击表格中的“编辑或查看优惠券按钮”
    handleEdit (index, row, state) {
      let data = this.filterFormFro.tableData
      this.editForm.index = index
      this.editForm.couponId = data[index].couponId
      this.editForm.couponName = data[index].couponName
      this.editForm.isFixed = data[index].isFixed
      this.editForm.airportName = data[index].airportName
      this.editForm.airportId = data[index].airportId
      this.editForm.businessName = data[index].placeName
      this.editForm.terminalName[0] = data[index].terminalName
      this.editForm.terminalId[0] = data[index].terminalId
      this.editForm.businessAllName = data[index].placeName + '(' + data[index].airportTerminal + ')'
      this.editForm.peopleLimit = data[index].peopleLimit
      this.editForm.fullUse = data[index].fullUse
      this.editForm.onlineTime = this.formatDateFro(new Date(data[index].onlineTime))
      this.editForm.effectiveTime = this.formatDateFro(new Date(data[index].effectiveTime))
      this.editForm.expireTime = this.formatDateFro(new Date(data[index].expireTime))
      this.editForm.limitNum = data[index].limitNum
      this.editForm.issuedNum = data[index].issuedNum
      this.editForm.issuedType = data[index].issuedType
      this.editForm.takenNum = data[index].takenNum
      this.editForm.isDelete = data[index].isDelete
      this.editForm.baseNum = data[index].baseNum
      this.editForm.couponSendType = parseInt(data[index].couponSendType)
      this.editForm.value = parseInt(data[index].value)
      this.editForm.isFixedValue = true
      this.editForm.airportList[0] = data[index].figureThree + ' ' + data[index].airportName
      this.editForm.airportList[1] = data[index].terminalName
      if (state === '已失效') { // 若为已失效则只能查看优惠券详情，不能编辑任何内容
        this.detailVisable = true
        this.editForm.couponSendType === '1' ? this.editForm.couponSendTypeValue = '领取' : this.editForm.couponSendTypeValue = '派发'
        this.editForm.isFixedValue ? this.editForm.isFixedValueContent = '定额' : this.editForm.isFixedValueContent = ''
      } else {
        this.editVisable = true
        if (state === '已生效') { // 若为已生效则只能修改“基数”和“失效时间”
          this.isEdit = true
        } else {
          this.isEdit = false
        }
      }
    },
    // 表格点击“删除”按钮
    handleDelete (index, row) {
      this.deleteForm.couponId = row.couponId
      this.deleteForm.couponName = row.couponName
      this.$confirm('确定删除优惠券吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteCouponListFro()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    setDeleteFro () {
      this.noteVisible = false
      this.$message.success('优惠券<' + this.deleteForm.couponName + '>已删除')
    },
    submitSearch () {
      this.filterFormFro.currentPage = 1
      this.getCouponListFro()
    }
  }
}
</script>